﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Collections;

namespace CF.Service
{
    public class FileHelper
    {

        #region 获取项目根路径
        /// <summary>
        /// 获取项目根路径
        /// </summary>
        /// <returns>提示信息</returns>
        public static string SolutionPath()
        {
            string solutionPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            if (solutionPath[solutionPath.Length - 1] != '\\') solutionPath = solutionPath + "\\";
            return solutionPath;
        }
        #endregion

        #region 获取文件字符串
        /// <summary>
        /// 获取文件字符串
        /// </summary>
        /// <param name="filepath">文件名称</param>
        /// <returns>提示信息</returns>
        public static string ReadFile(string filepath)
        {
            filepath = SolutionPath() + filepath;
            string content = "";
            FileStream fs = new FileStream(filepath, FileMode.Open);//为读文件建立文件流
            StreamReader reader = new StreamReader(fs, Encoding.UTF8);
            content = reader.ReadToEnd();//把流中的全部内容放入文本框中显示出来。
            fs.Close();
            return content;
        }
        #endregion

        #region 写入文件
        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="text">需写入的字符串</param>
        /// <param name="filepath">文件名称</param>
        /// <returns>提示信息</returns>
        public static void WriteFile(string text , string filepath)
        {
            filepath = SolutionPath() + filepath;
            FileStream fs = new FileStream(filepath, FileMode.Create);
            StreamWriter writer = new StreamWriter(fs, Encoding.UTF8);
            writer.Write(text);
            writer.Flush();//把内存中未写盘的内容写盘。
            writer.Close();
        }
        #endregion

        #region 续写文件
        /// <summary>
        /// 续写文件
        /// </summary>
        /// <param name="text">需写入的字符串</param>
        /// <param name="filepath">文件名称</param>
        /// <returns>提示信息</returns>
        public static void WriteDataFile(string text, string filepath)
        {
            string oldText = ReadFile(filepath);
            WriteFile(oldText + text, filepath);
        }
        #endregion

        #region 创建文件夹
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="Folder">文件夹名称</param>
        /// <returns>提示信息</returns>
        public static void CreateFolder(string Folder)
        {
            string solutionPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            if (solutionPath[solutionPath.Length - 1] != '\\') solutionPath = solutionPath + "\\";
            string path = solutionPath + Folder;
            Encoding code = Encoding.GetEncoding("utf-8");
            //如果文件不存在,将创建文件
            if (!Directory.Exists(path))
            {
                // Create the directory it does not exist.
                Directory.CreateDirectory(path);
            }
        }
        #endregion

        #region 截取字符串
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="fileName">起始字符串</param>
        /// <param name="fileName">结束字符串</param>
        /// <returns>提示信息</returns>
        public static string CutString(string str, string begin, string end)
        {
            string str_ = string.Empty;
            Regex reg = new Regex("(?<=(" + begin + "))[.\\s\\S]*?(?=(" + end + "))", RegexOptions.Multiline | RegexOptions.Singleline);
            foreach (Match match in reg.Matches(str))
            {
                str_ += match.Value;
            }
            return str_;
        }
        #endregion

        #region 去除HTML标记
        /// <summary>
        /// 去除HTML标记
        /// </summary>
        /// <param name="strHtml">待转化的字符串</param>
        /// <returns>经过转化的字符串</returns>
        public static string RemoveHtml(string strHtml)
        {
            Regex objRegExp = new Regex("<(.|\n)+?>");
            string strOutput = objRegExp.Replace(strHtml, "");
            strOutput = strOutput.Replace("<", "");
            strOutput = strOutput.Replace(">", "");
            return strOutput.Trim();
        }
        #endregion

        #region 去除HTML标记（<P>、<IMG>、<BR>除外）
        /// <summary>
        /// 去除HTML标记
        /// </summary>
        /// <param name="strHtml">待转化的字符串</param>
        /// <returns>经过转化的字符串</returns>
        public static string RemoveHtmlSP(string strHtml)
        {
            Regex objRegExp = new Regex(@"(?i)<(?!p|br|img).*?>", RegexOptions.IgnoreCase);
            return objRegExp.Replace(strHtml, "");
            //return regex.Replace(strHtml, "").Replace("&nbsp;", "").Replace("\n", "").Replace("\r", "");
        }
        #endregion

        #region 获取Html
        /// <summary>
        /// 创建Cookie
        /// </summary>
        /// <param name="strHtml">待转化的字符串</param>
        /// <returns>经过转化的字符串</returns>
        public static string PostAndGetHTML(string targetURL, CookieContainer cc, byte[] data)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetURL);
            request.Method = "POST";    //post
            request.ContentType = "x-www-form-urlencoded";
            request.ContentLength = data.Length;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727)";
            request.CookieContainer = cc;
            //request.KeepAlive = false;

            Stream newStream1 = request.GetRequestStream();
            newStream1.Write(data, 0, data.Length);
            newStream1.Close();
            //request.CookieContainer = cc;
            HttpWebResponse response1 = (HttpWebResponse)request.GetResponse();
            //cc.Add(response1.Cookies);
            Stream stream1 = response1.GetResponseStream();
            string result = new StreamReader(stream1, System.Text.Encoding.UTF8).ReadToEnd();
            return result;
        }
        #endregion

        #region 获取Session
        /// <summary>
        /// 创建Cookie
        /// </summary>
        /// <param name="strHtml">待转化的字符串</param>
        /// <returns>经过转化的字符串</returns>
        public static string PostAndGetSession(string targetURL, CookieContainer cc, Hashtable param)
        {
            //prepare the submit data
            string formData = "";
            foreach (DictionaryEntry de in param)
            {
                formData += de.Key.ToString() + "=" + de.Value.ToString() + "&";
            }
            if (formData.Length > 0)
                formData = formData.Substring(0, formData.Length - 1); //remove last '&'
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(formData);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetURL);
            request.Method = "POST";    //post
            request.ContentType = "x-www-form-urlencoded";
            request.ContentLength = data.Length;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727)";
            request.CookieContainer = cc;
            request.Credentials = CredentialCache.DefaultCredentials;
            //request.KeepAlive = false;

            Stream newStream1 = request.GetRequestStream();
            newStream1.Write(data, 0, data.Length);
            newStream1.Close();
            //request.CookieContainer = cc;
            HttpWebResponse response1 = (HttpWebResponse)request.GetResponse();
            string sessionid = response1.Headers.Get("Set-Cookie");
            if (!string.IsNullOrEmpty(sessionid))
            {
                sessionid = CutString(sessionid, "ASP.NET_SessionId=", ";");
            }
            return sessionid;
        }
        #endregion

        //public static string GetFileString(string fileName)
        //{
        //    string solutionPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
        //    if (solutionPath[solutionPath.Length - 1] != '\\') solutionPath = solutionPath + "\\";
        //    string filePath = solutionPath + fileName;
        //    Encoding code = Encoding.GetEncoding("utf-8");
        //    //如果文件不存在,将创建文件
        //    if (!File.Exists(filePath))
        //    {
        //        File.Create(filePath);
        //    }

        //    StreamReader sr = null;
        //    string strOld = "";
        //    try
        //    {
        //        sr = new StreamReader(filePath, code);
        //        strOld = sr.ReadToEnd(); // 读取文件
        //        sr.Close();
        //        return strOld;
        //    }
        //    catch (Exception exp)
        //    {
        //        //return exp.Message;
        //    }
        //    return "";
        //}

        //public static bool WriteFileString(string str, string fileName)
        //{
        //    string solutionPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
        //    if (solutionPath[solutionPath.Length - 1] != '\\') solutionPath = solutionPath + "\\";
        //    string filePath = solutionPath + fileName;
        //    Encoding code = Encoding.GetEncoding("utf-8");
        //    //如果文件不存在,将创建文件
        //    if (!File.Exists(filePath))
        //    {
        //        File.Create(filePath);
        //        WriteFileString(str, fileName);
        //        return true;
        //    }
        //    StreamWriter sw = null;
        //    // 写文件 
        //    try
        //    {
        //        sw = new StreamWriter(filePath, false, code);
        //        sw.Write(str);
        //        sw.Flush();
        //        sw.Close();
        //        return true;
        //    }
        //    catch (Exception exp)
        //    {
        //        return false;
        //    }
        //    return false;
        //}
        



    }
}